package com.hundsun.yr.universal.p2p.utils;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

import com.hundsun.yr.universal.library.utils.MathUtils;

public class LocationUtils {
	
	private double latitude=-200;  
	private double longitude =-200;  
	  
	private Context mContext;
	private LocationManager locationManager;
	private LocationListener locationListener;

	public LocationUtils(Context context){
		this.mContext= context;
		getLocation(context);
	}
	
	public void getLocation(Context context){

		locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
		if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
			if (location != null) {
				latitude = location.getLatitude();
				longitude = location.getLongitude();
			} else {

				// Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
// Provider被enable时触发此函数，比如GPS被打开
// Provider被disable时触发此函数，比如GPS被关闭
// 当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
// 经度
// 纬度
				locationListener = new LocationListener() {

					// Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
					@Override
					public void onStatusChanged(String provider, int status,Bundle extras) {
					}

					// Provider被enable时触发此函数，比如GPS被打开
					@Override
					public void onProviderEnabled(String provider) {

					}

					// Provider被disable时触发此函数，比如GPS被关闭
					@Override
					public void onProviderDisabled(String provider) {

					}

					// 当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
					@Override
					public void onLocationChanged(Location location) {
						if (location != null) {
							Logs.e("Map", "Location changed : Lat: " + location.getLatitude() + " Lng: " + location.getLongitude());
							latitude = location.getLatitude(); // 经度
							longitude = location.getLongitude(); // 纬度
						}
					}
				};
				locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, locationListener);
				Location location1 = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
				if (location1 != null) {
					latitude = location1.getLatitude(); // 经度
					longitude = location1.getLongitude(); // 纬度
				}
			}
		}
	}
	
	
	/**
	 * 获取精度
	 * @return
	 */
	public String getLatitude(){
//		getLocation(mContext);
		return MathUtils.double2string(latitude);
	}
	/**
	 * 获取纬度
	 * @return
	 */
	public String getLongitude(){
//		getLocation(mContext);
		return MathUtils.double2string(longitude);
	}

	/**
	 * 移除位置获取
	 */
	public void removeLocationManagerListener(){
		locationManager.removeUpdates(locationListener);
	}
}
